package lex.mtd.core;

import java.io.File;
import java.io.IOException;
import java.util.Comparator;

import org.lex.utils.SystemProperties;


public class FileBlock implements java.io.Serializable
{
	public transient static final Comparator<FileBlock> START_POSITION_COMPARATOR;
	public transient static final Comparator<FileBlock> REMAIN_LENGTH_COMPARATOR;
	private static final long serialVersionUID = -6773312093912523912L;
	static
	{
		START_POSITION_COMPARATOR = new Comparator<FileBlock>(){
			@Override
			public int compare( FileBlock o1, FileBlock o2 )
			{
				return Long.valueOf( o1.start ).compareTo( o2.start );
			}
		};
		REMAIN_LENGTH_COMPARATOR = new Comparator<FileBlock>(){
			@Override
			public int compare( FileBlock o1, FileBlock o2 )
			{
				return Long.valueOf( o1.getRemainLength() ).compareTo( o2.getRemainLength() );
			}
		};
	}
	private File file = null;
	// =======================
	private int id = 0;
	// �����������ʼ��ַ
	long start = 0L; // used in FilePartSet
	// ���ص�ַ���յ��ַ
	long end = 0L; // used in FilePartSet
	// �Ѿ���ɵ��ֽ���
	long offset = 0L;// used in DownloadThread

	public FileBlock( int id, File dir, String basename, String extname )
	{
		this.id = id;
		// like "notepad.exe.part.11"
		this.file = new File( dir, basename + "." + extname + ".part." + id );
		if( false == file.exists() || false == file.isFile() )
			try
			{
				file.createNewFile();
			}
			catch( IOException e )
			{
				e.printStackTrace();
			}
	}

	public boolean isFinished()
	{
		return 0 == this.getRemainLength();
	}

	public String getFileName()
	{
		return file.getName();
	}

	public File getFile()
	{
		return file;
	}

	public long getStartPosition()
	{
		return this.start;
	}

	/**
	 * �ļ���ĳ���
	 * 
	 * @return
	 */
	public long getLength()
	{
		return this.end - this.start;
	}

	public long getOffset()
	{
		return this.offset;
	}

	public long getRemainLength()
	{
		return this.getLength() - this.getOffset();
	}

	public int getID()
	{
		return id;
	}

	@Override
	public String toString()
	{
		StringBuilder buf = new StringBuilder();
		String nl = SystemProperties.lineSeparator();
		buf.append( "file  : " ).append( file.getName() ).append( nl );
		buf.append( "start : " ).append( start ).append( nl );
		buf.append( "end   : " ).append( end ).append( nl );
		buf.append( "length: " ).append( this.getLength() ).append( nl );
		buf.append( "offset: " ).append( this.getOffset() );
		return buf.toString();
	}
}
